package com.example.demo.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author： litao
 * @date： 2022-01-25 18:03
 */
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean:3
    @Bean(name = "getShiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager getDefaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(getDefaultWebSecurityManager);


        //添加shiro内置过滤器
        /**
         * anon : 无需认证,直接访问
         * authc : 必须认证才能访问
         * user : 必须拥有记住我才能访问
         * perms :拥有对某个资源的权限才能访问
         * role : 拥有某个角色权限才能访问
         */
        //拦截
        Map<String, String> map = new LinkedHashMap<>();

        //授权
        map.put("/user/add", "perms[user:add]");
        map.put("/user/update", "perms[user:update]");

//        map.put("/user/add","authc");
//        map.put("/user/update","authc");
        //支持通配符
        map.put("/user/*", "authc");


        bean.setFilterChainDefinitionMap(map);

        //设置登录请求
        bean.setLoginUrl("/toLogin");

        //未授权页面
        bean.setUnauthorizedUrl("/noauth");



        return bean;
    }

    //DefaultWebSecurityManager:2 @Qualifier("userRealm") 指定方法名称
    @Bean(name = "getDefaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        defaultWebSecurityManager.setRealm(userRealm);

        return defaultWebSecurityManager;
    }

    //创建realm对象,需要自定义类:1
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }

}
